<template>
  <div class="vue-box">
    <div class="c-panel">
      <el-row>
        <!--模糊查询-->
        <el-form :inline="true" size="small">
            <el-form-item label="菜单名称：">
              <el-input type="text" size="small" v-model="query.menuName" placeholder="模糊查询"></el-input>
            </el-form-item>
            <el-form-item label="状态：">
              <el-select size="small" v-model="query.status" placeholder="请选择" clearable>
                <el-option label="启用" value="1"></el-option>
                <el-option label="停用" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="权限标识：">
                  <el-input type="text" size="small" v-model="query.permission" placeholder="模糊查询"></el-input>
              </el-form-item>
            <el-form-item>
              <el-button style="min-width: 0px;" type="primary" icon="el-icon-search" @click="screen()">查询</el-button>
            </el-form-item>
        </el-form>
        <!--全局功能按钮-->
        <el-row>
            <el-col :span="1.5" class="firstBtn">
              <el-button size="small" type="success" icon="el-icon-plus" plain @click="add('')">新增</el-button>
            </el-col>
            <el-col :span="1.5" class="btn">
              <el-button size="small" type="primary" icon="el-icon-sort" plain @click="handleExpand()">展开/折叠</el-button>
            </el-col>
            <el-col :span="1.5" class="btn">
              <el-button size="small" type="info" icon="el-icon-refresh" plain @click="query.menuName='',query.permission='',query.status='',f5()">重置</el-button>
            </el-col>
        </el-row>
        <!--组织列表-->
        <el-table
          :data="tableData" style="width: 100%" row-key="id" ref="table" v-loading="state.loading" 
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
          <el-table-column prop="menuName" label="菜单名称" width="180">
          </el-table-column>
          <el-table-column label="图标" width="60" align="center">
            <template slot-scope="s">
              <i :class="s.row.icon" :title="s.row.menuName"></i>
            </template>
          </el-table-column>
          <el-table-column prop="path" label="组件路径" width="220" align="center">
          </el-table-column>
          <el-table-column prop="url" label="接口地址" width="200" align="center">
          </el-table-column>
          <el-table-column prop="permission" label="权限标识" width="160" align="center">
          </el-table-column>
          <el-table-column label="状态" prop="tag" width="80" align="center">
            <template slot-scope="scope">
              <el-tag
                :type="scope.row.status === '1' ? 'primary' : 'info'"
                disable-transitions>{{sa.getDictByidAndlabel('1', scope.row.status)}}</el-tag>
            </template>
          </el-table-column>         
          <el-table-column prop="createTime" label="创建时间" width="150" align="center">
          </el-table-column>         
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                size="mini" type="success" icon="el-icon-plus"
                @click="add(scope.row,'rowadd')"></el-button>
              <el-button size="mini" type="primary" icon="el-icon-edit"
                @click="edit(scope.row)"></el-button>
              <el-button
                size="mini" type="danger" icon="el-icon-delete"
                @click="state.delDialogVisible=true,info=scope.row,openWarning('注意：此操作会导致该菜单的下级资源也会被删除!')"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--对话框相关-->
        <el-dialog
          title="菜单信息" :modal-append-to-body='false' top='5vh' v-if="state.dialogVisible"
          :visible.sync="state.dialogVisible">
          <menuInfo :menu="JSON.stringify(info)" :idList="idList" :nameList="nameList" :menuTree="tableData" :displayType="state.displayType" :addType="state.addType"></menuInfo>
        </el-dialog>
        <el-dialog
          title="提示" :modal-append-to-body='false'
          :visible.sync="state.delDialogVisible" width="30%">
          <span>确认删除该菜单？</span>
          <span slot="footer" class="dialog-footer">
            <el-button @click="state.delDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="del()">确 定</el-button>
          </span>
        </el-dialog>
      </el-row>
    </div>
  </div>
</template>

<script>
import menuInfo from './menu-info.vue'
export default {
  data(){
    return{
        /*查询参数 */
        query:{
          menuName:'',
          status:'',
          permission:''
        },
        tableData:[],//树结构
        info:{},//当前操作菜单
        idList:[],//一、二级菜单的id数组
        nameList:[],//一、二级菜单的name数组
        /*各种状态*/
        state:{
          loading:false,//加载状态
          displayType:'',//新增/修改对话框显示类型
          delDialogVisible:false,//删除确认框的显示状态
          dialogVisible:false,//新增/修改对话框的显示状态
          addType:'',//新增的类型
          isExpand:false//当前的列表是否全展开
        },
    }
  },
  components:{ menuInfo},
  methods:{
    //刷新
    f5(){
      this.state.loading=true;
      //获取菜单树
      this.request('/api/menu/getMenuTree').then(res=>{
        if(!res){return}
        this.tableData=this.refMenuList(res.data,"displaceStatus")
        this.state.loading=false;
      })
    },
    //新增
    add(data,type){
      if(this.zm.checkAuth('menu:add')){
        this.info=data
        this.state.displayType='add'
        //如果是组织行新增，则父级菜单固定
        if(type==="rowadd"){
          this.state.addType="rowadd"
        }else{
          this.state.addType=""
        }
        this.state.dialogVisible=true
      }else{
        this.$message.error("您暂无<新增菜单>权限！")
      }
    },
    //新增的回调
    addCallback(){
      //列表刷新
      this.f5()
      //菜单栏刷新
      this.$bus.$emit("updateMenu")
      //刷新用户权限信息
      this.$bus.$emit('refUserPerm')
      this.$message.success("新增成功");
      this.state.dialogVisible=false
    },
    //修改
    edit(data){
      if(this.zm.checkAuth('menu:update')){
        this.info=data
        this.state.displayType='edit'
        this.state.dialogVisible=true
      }else{
        this.$message.error("您暂无<修改菜单>权限！")
      }
      
    },
    //修改的回调
    updateCallback(){
      //列表刷新
      this.f5()
      //菜单栏刷新
      this.$bus.$emit("updateMenu")
      //刷新用户权限信息
      this.$bus.$emit('refUserPerm')
      this.$message.success("修改成功");
      this.state.dialogVisible=false
    },
    //删除
    del(){
      this.state.loading=true;
      //console.log(this.info);
      this.request('/api/menu/del?id='+this.info.id).then(res=>{
        if(!res){return}
        this.f5()
        //刷新菜单
        this.$bus.$emit("updateMenu")
        this.tableData=this.refMenuList(this.tableData,"del",this.info)
        //刷新用户权限信息
        this.$bus.$emit('refUserPerm')
        this.$message.success("删除成功");
        this.state.delDialogVisible=false;
      })
      this.state.loading=false;
    },
    //模糊查询
    screen(){
      //console.log(this.query);
      let params=this.query;
      this.request('/api/menu/screen',params).then(res=>{
        if(!res){return}
        this.tableData=this.refMenuList(res.data,"displaceStatus")
      })
    },
    //是否展开table(展开与折叠切换)
    handleExpand() {
      this.state.isExpand = !this.state.isExpand
      this.$nextTick(() => {
        this.forArr(this.tableData, this.state.isExpand)
      })
    },
    //遍历
    forArr(arr, isExpand) {
      arr.forEach(i => {
        //toggleRowExpansion(i,isExpand)用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected为true则选中）
        //因为是全加载，数据一开始就是全的，所以只要改展开状态即可
        this.$refs.table.toggleRowExpansion(i, isExpand)
        if (i.children) {
          this.forArr(i.children, isExpand)
        }
      })
    },
    //刷新菜单列，type:刷新类型，删除的菜单对象
    refMenuList(list,type,item,newTableData){
      for (let index = 0; index < list.length; index++) {
        let element = list[index];
        //console.log(element);
        //状态转换
        if(type==="displaceStatus"){
          //element=this.sa.displaceStrStatus(element);
        }
        if(type!=="displaceStatus"&&element.id===item.id){
          if(type==="del"){
            list.splice(index,1)
            return;
          }
        }
        if (element.children && element.children.length > 0) {
            this.refMenuList(element.children,type,item,newTableData);	// 递归处理
        }
      }
      return list;
    },
    //弹出警告提示框，参数为警告信息
    openWarning(msg) {
      this.$notify({
        title: '警告',
        message: msg,
        type: 'warning'
      });
    },
    //对话框取消
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
        done();
        })
        .catch(_ => {});
    }
  },
  mounted(){
    this.f5()
    //获取一二级菜单的idList和nameList
    this.request('/api/menu/getHasChildMenu').then(res=>{
      if(!res){return}
      this.idList=res.data.idList
      this.nameList=res.data.nameList
    })
    //取消修改的回调绑定
    this.$bus.$on("noUpdate",()=>{this.state.dialogVisible=false})
    //修改的回调绑定
    this.$bus.$on("updateMenuCallback",this.updateCallback)
    //新增的回调绑定
    this.$bus.$on("addMenuCallback",this.addCallback)
  },
  beforeDestroy(){
    this.$bus.$off(['updateMenuCallback','addMenuCallback','noUpdate'])
  }
}
</script>

<style scoped>
/**模糊查询样式*/
.el-form-item--small /deep/ .el-form-item__content, /deep/ .el-form-item--small .el-form-item__label  {
	font-size:14px;
	font-weight:900;
}
/*模糊搜索表单右移5px，对齐全局按钮和数据table*/
/deep/.c-panel .el-form{
	margin-left:-5px
}
/*表格样式 */
/deep/ .el-table {
  margin-left:10px;
}
/deep/ .el-table th.el-table__cell {
  background-color: aliceblue;
}
/*按钮与表格的对齐间距等等 */
.firstBtn{
  padding-left:10px;
  padding-right:5px;
  margin-bottom: 5px;
}
.btn{
  padding-right:5px;
  margin-bottom: 5px;
}
</style>